﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OrBitDataModule.CustomEventHandler;

namespace OrBitDataModule.Adaptor
{
    public class HttpServer
    {
        public int Port { get; }

        public HttpServer(int port)
        {
            this.Port = port;
            CreateHttpServer();
        }

        /// <summary>
        /// 请求事件
        /// </summary>
        public event EventHandler<HttpRequestEventArgs> OnHttpRequest;
        /// <summary>
        /// 发生异常
        /// </summary>

        public event EventHandler<Exception> OnHttpError;

        private HttpListener listener;
        //private Thread listenerThread;

        /// <summary>
        /// 是否在监听
        /// </summary>
        public bool IsListening => listener.IsListening;

        private void CreateHttpServer()
        {
            listener = new HttpListener();
        }
        /// <summary>
        /// 开始服务
        /// </summary>
        public async void StartHttpServer()
        {
            try
            {
                listener.Prefixes.Clear();
                List<string> ips = GetLocalIPv4Addresses();
                listener.Prefixes.Add($"http://localhost:{Port}/");
                listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
                foreach (string ip in ips)
                {
                    listener.Prefixes.Add($"http://{ip}:{Port}/");
                }
                await HandleHttpRequests();
            }
            catch (Exception ex)
            {
                OnHttpError?.Invoke(listener, ex);
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        public void StopHttpServer()
        {
            if (listener.IsListening)
            {
                listener?.Stop();
            }
        }


        static List<string> GetLocalIPv4Addresses()
        {
            List<string> ipv4Addresses = new List<string>();

            // 获取本机所有网络接口信息
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                    networkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                {
                    IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                    foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            ipv4Addresses.Add(ip.Address.ToString());
                        }
                    }
                }
            }
            return ipv4Addresses.Where(i => !i.StartsWith("169.254")).ToList();
        }
        /// <summary>
        /// 开始接听处理请求
        /// </summary>
        /// <returns></returns>
        private Task HandleHttpRequests()
        {
            return Task.Run(() =>
            {
                listener.Start();
                while (listener.IsListening)
                {
                    try
                    {
                        HttpListenerContext context = listener.GetContext();
                        ProcessRequest(context);
                    }
                    catch (HttpListenerException ex)
                    {
                        OnHttpError?.Invoke(listener, ex);
                    }
                }
            });

        }

        private void ProcessRequest(HttpListenerContext context)
        {
            OnHttpRequest?.Invoke(listener, new HttpRequestEventArgs(context.Request, context.Response));
        }
    }
}
